import React, { useState, useEffect, useRef } from 'react';
import styles from './image.module.css';

const LazyImage = ({ src, alt, className, placeholder = '' } => {
  const [isLoaded, setIsLoaded] = useState(false);
  const [isVisible, setIsVisible] = useState(false);
  const imgRef = useRef(null);
  const observerRef = useRef(null);

  // 图片加载完成处理
  const handleLoad = () => {
    setIsLoaded(true);
  };

  // 设置 IntersectionObserver 监听元素可见性
  useEffect(() => {
    // 检查浏览器是否支持 IntersectionObserver
    if ('IntersectionObserver' in window) {
      observerRef.current = new IntersectionObserver((entries) => {
        const [entry] = entries;
        if (entry.isIntersecting) {
          setIsVisible(true);
          // 一旦图片可见，就停止观察
          if (observerRef.current) {
            observerRef.current.unobserve(imgRef.current);
          }
        }
      }, {
        rootMargin: '200px', // 提前200px加载
        threshold: 0.1
      });

      if (imgRef.current) {
        observerRef.current.observe(imgRef.current);
      }
    } else {
      // 不支持 IntersectionObserver 的浏览器，直接加载图片
      setIsVisible(true);
    }

    return () => {
      if (observerRef.current) {
        observerRef.current.disconnect();
      }
    };
  }, []);

  return (
    <div className={`${styles['lazy-image-container']} ${className || ''}`} ref={imgRef}>
      {/* 占位符 */}
      {!isLoaded && (
        <img
          src={placeholder}
          alt="Loading placeholder"
          className={styles['placeholder']}
        />
      )}
      {/* 实际图片 */}
      {isVisible && (
        <img
          src={src}
          alt={alt}
          onLoad={handleLoad}
          className={`${styles['image']} ${isLoaded ? styles['loaded'] : ''}`}
        />
      )}
    </div>
  );
};

export default LazyImage;